package springboot.config;

import springboot.domain.Permission;
import springboot.domain.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import springboot.service.UserService;

import javax.annotation.Resource;

public class UserRealm extends AuthorizingRealm {
    @Resource
    private UserService userService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String userName = (String) token.getPrincipal();
        String password = new String((char[]) token.getCredentials());//证明 例如 密码
        User user = userService.findByUserName(userName);
        if (user == null) {
            throw new UnknownAccountException("找不到该用户！");
        } else if (!password.equals(user.getPassword())) {
            throw new IncorrectCredentialsException("密码不匹配！");
        }
        // 建立一个认证模块，包括身份证明信息
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                user,//传入user对像
                user.getPassword(), getName());
        return authenticationInfo;
    }
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //授权 新建一个授权模块 SimpleAuthorizationInfo 把 权限赋值给当前的用户
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        //如果身份认证的时候没有传入User对象，这里只能取到userName
        // 也就是SimpleAuthenticationInfo构造的时候第一个参数传递需要User对象
        User user  = (User)principals.getPrimaryPrincipal();
        //添加角色
        authorizationInfo.addRole(user.getRole().getRole());
        for(Permission p:user.getRole().getPermissions()){
            //添加权限
            authorizationInfo.addStringPermission(p.getPermission());
        }
        return authorizationInfo;
    }
}



